#coding:utf-8

import aiomysql
from www.log import logging
from functools import wraps

logger = logging.getLogger(__file__)

async def create_pool(loop, **kw):
    logger.info('create database connection pool...')
    global __pool
    __pool = await aiomysql.create_pool(
        host=kw.get('host', 'localhost'),
        port=kw.get('port', 3306),
        user=kw['user'],
        password=kw['password'],
        db=kw['db'],
        charset=kw.get('charset', 'utf8'),
        autocommit=kw.get('autocommit', True),
        maxsize=kw.get('maxsize', 10),
        minsize=kw.get('minsize', 1),
        loop=loop,
    ) 

def parser_arg(k: int):
    '''
    装饰器，使非list的第k个参数转为list
    >>> @parser_arg(1)
    >>> def test(arg1, arg2):
    ...     print(arg1, arg2)
    >>> test(1, 2)
    1 [2]
    '''
    def parser_arg_w(func):
        @wraps(func)
        def wrapper(*args, **kw):
            if args != None and len(args) > k and not isinstance(args[k], list):
                new_args = []
                for i in range(len(args)):
                    if i == k:
                        new_args.append([args[i], ])
                    else:
                        new_args.append(args[i])
                return func(*new_args, **kw)
            return func(*args, **kw)
        return wrapper
    return parser_arg_w

def log_arg(k: int):
    '''
    装饰器，打印第k个参数
    '''
    def log_arg_w(func):
        @wraps(func)
        def wrapper(*args, **kw):
            if args:
                logger.info('SQL:%s' % args[k])
            else:
                raise Exception('no args')
            return func(*args, **kw)
        return wrapper
    return log_arg_w

def create_args_string(num: int):
    '''
    创建sql占位符
    >>> print (create_args_string(3))
    '?, ?, ?'
    '''
    return ', '.join(['?'] * num)


@log_arg(0)
@parser_arg(1)
async def select(sql: str, args: list or str, size=None):
    '''
    数据库-查
    '''
    global __pool
    async with __pool.get() as conn:
        async with conn.cursor(aiomysql.DictCursor) as cur:
            await cur.execute(sql.replace('?', '%s'), args or ())
            if size:
                rs = await cur.fetchmany(size)
            else:
                rs = await cur.fetchall()
        logger.info('rows returned:%s' % len(rs))
        return rs

@log_arg(0)
@parser_arg(1)
async def execute(sql: str, args: list or str, autocommit=True):
    '''
    数据库-增删改
    '''
    global __pool
    async with __pool.get() as conn:
        if not autocommit:
            await conn.begin()
        try:
            async with conn.cursor(aiomysql.DictCursor) as cur:
                await cur.execute(sql.replace('?', '%s'), args or ())
                affected = cur.rowcount
            if not autocommit:
                await conn.commit()
        except BaseException:
            if not autocommit:
                await conn.rollback()
            raise
        return affected


class ModelMetaclass(type):

    def __new__(cls, name, bases, attrs):
        if name=='Model':
            return type.__new__(cls, name, bases, attrs)
        tableName = attrs.get('__table__', None) or name
        logger.info('found model: %s (table: %s)' % (name, tableName))
        mappings = dict()
        fields = []
        primaryKey = None
        for k, v in attrs.items():
            if isinstance(v, Field):
                logger.info('found mapping: %s ==> %s' % (k, v))
                mappings[k] = v
                if v.primary_key:
                    # 找到主键:
                    if primaryKey:
                        raise Exception('Duplicate primary key for field: %s' % k)
                    primaryKey = k
                else:
                    fields.append(k)
        if not primaryKey:
            raise Exception('Primary key not found.')
        for k in mappings.keys():
            attrs.pop(k)
        escaped_fields = list(map(lambda f: '`%s`' % f, fields))
        attrs['__mappings__'] = mappings # 保存属性和列的映射关系
        attrs['__table__'] = tableName
        attrs['__primary_key__'] = primaryKey # 主键属性名
        attrs['__fields__'] = fields # 除主键外的属性名
        attrs['__select__'] = 'select `%s`, %s from `%s`' % (primaryKey, ', '.join(escaped_fields), tableName)
        attrs['__insert__'] = 'insert into `%s` (%s, `%s`) values (%s)' % (tableName, ', '.join(escaped_fields), primaryKey, create_args_string(len(escaped_fields) + 1))
        attrs['__update__'] = 'update `%s` set %s where `%s`=?' % (tableName, ', '.join(map(lambda f: '`%s`=?' % (mappings.get(f).name or f), fields)), primaryKey)
        attrs['__delete__'] = 'delete from `%s` where `%s`=?' % (tableName, primaryKey)
        return type.__new__(cls, name, bases, attrs)


class Model(dict, metaclass=ModelMetaclass):
    def __init__(self, **kw):
        super(Model, self).__init__(**kw)

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r'Model object hash no attribute %s' % key)
    
    def __setattr__(self, key, value):
        self[key] = value
    
    def getValue(self, key):
        return getattr(self, key, None)

    def getValueOrDefault(self, key):
        value = getattr(self, key, None)
        if value is None:
            field = self.__mappings__[key]
            if field.default is not None:
                value = field.default() if callable(field.default) else field.default
                logger.info('using default value for %s:%s' % (key, str(value)))
                setattr(self, key, value)
        return value

    @classmethod
    async def find(cls, id: int):
        '''
        根据主键查找类
        '''
        rs = await select('%s where `%s`=?' % (cls.__select__, cls.__primary_key__), id, 1)
        if len(rs) == 0:
            return None
        return cls(**rs[0])

    async def save(self):
        '''
        将实例持久化
        '''
        args = list(map(self.getValueOrDefault, self.__fields__))
        args.append(self.getValueOrDefault(self.__primary_key__))
        rows = await execute(self.__insert__, args)
        if rows != 1:
            logging.warn('failed to insert record: affected rows: %s' % rows)

class Field(object):

    def __init__(self, name, column_type, primary_key, default):
        self.name = name
        self.column_type = column_type
        self.primary_key = primary_key
        self.default = default

    def __str__(self):
        return '<%s, %s:%s>' % (self.__class__.__name__, self.column_type, self.name)


if __name__ == '__main__':
    @parser_arg(1)
    def test(l, k):
        print (l, k)

    @log_arg
    def test2(sql, asdl, das):
        pass
    # logger.info('test')
    # logger.debug('test')
    # logger.error('test')
    # test2('select * from user', 5, 6)
    print(create_args_string(5))
    #test(5, [7, 8])